package com.ahhwxx.lib.utils;

import android.content.Context;

import com.ahhwxx.lib.ACamera;
import com.ahhwxx.lib.IdentifyInfo;
import com.ym.android.engine.pn.OcrEngine;
import com.ym.android.vo.Plate;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * author : hades
 * date   : 3/21/22
 * desc   :快速识别
 */
public class QuickRecognition {
    private static QuickRecognition instance;
    private OcrEngine ocrEngine;
    private Plate plate;
    private Context mContext;

    private QuickRecognition(Context context) {
        mContext = context;
        ocrEngine = new OcrEngine();
        plate = new Plate();
    }

    public static synchronized QuickRecognition getInstance(Context context) {
        if (instance == null) {
            instance = new QuickRecognition(context);
        }
        return instance;
    }

    public IdentifyInfo quickPhoto(String path) {
        try {
            plate = ocrEngine.recognize(mContext, path, path);
            if (plate.getRecogStatus() == OcrEngine.RECOG_OK) {
                try {
                    String result = new String(plate.getCharInfo(), "GBK");
                    String json = result.substring(0, result.lastIndexOf("}") + 1);
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        IdentifyInfo info = new IdentifyInfo();
                        info.setColor(jsonObject.getString("Color"));
                        info.setLayer(jsonObject.getString("Layer"));
                        info.setNum(jsonObject.getString("Num"));
                        return info;
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return null;
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
